package cn.mayday.algorithms.year2021.month1.优先搜索二叉搜索;

/**
 * 二叉搜索树与双向链表
 *
 * 输入一棵二叉搜索树，将该二叉搜索树转换成一个排序的循环双向链表。
 * 要求不能创建任何新的节点，只能调整树中节点指针的指向。
 *
 * @author: mayday
 * @date: 2021/5/11 18:11
 * @version: 1.0
 */
public class Offer036TreeToDoublyList {
    class Node {
        public int val;
        public Node left;
        public Node right;

        public Node() {}

        public Node(int _val) {
            val = _val;
        }

        public Node(int _val,Node _left,Node _right) {
            val = _val;
            left = _left;
            right = _right;
        }
    };

    public static void main(String[] args) {

    }

    // 二叉搜索树转化为循环双向链表

    Node head; // 定义双向指针的两个节点 头结点
    Node pre; // 头结点的上一个节点

    public Node treeToDoublyList(Node root) {
        if (root == null) {
            return null;
        }

        dfs(root);

        head.left = pre;
        pre.right = head;

        return head;
    }

    private void dfs(Node current) {
        if (current == null) {
            return;
        }

        if (pre == null) {
            head = current;
        } else {
            pre.right = current;
        }

        pre = current;
        dfs(current.right);
    }
}
